<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 slot="header" class="login-title">用户登录</h2>

      <el-form
          ref="loginForm"
          :model="form"
          :rules="rules"
          label-width="80px"
          class="login-form"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="passWord">
          <el-input
              v-model="form.passWord"
              type="password"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
          >
            登录
          </el-button>
          <el-button
              type="text"
              @click="$router.push('/register')"
          >
            没有账号？去注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import { useRouter } from 'vue-router'
import userApi from '../api/user'
import auth from '../utils/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loginForm = ref(null)
const userInfo = ref({})
const userTypeText = ref('')

// 表单数据
const form = reactive({
  userName: '',
  passWord: ''
})

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  try {
    await loginForm.value.validate()
    const res = await userApi.login(form)

    if (res.code === 200) {
      // 1. 存储Token
      auth.setToken(res.data)
      ElMessage.success('登录成功')

      // 2. 重新获取用户信息（关键：此时Token已存储，可获取到最新用户信息）
      userInfo.value = auth.getUserInfo() || {}

      // 3. 重新计算用户类型文本
      if (userInfo.value.userType === 0) {
        userTypeText.value = '管理员'
      }
      if (userInfo.value.userType === 1) {
        userTypeText.value = '老师'
      }
      if (userInfo.value.userType === 2) {
        userTypeText.value = '学生'
      }

      // 4. 根据用户类型跳转（此时userTypeText已正确赋值）
      if (userTypeText.value === '学生') {
        router.push('/student')
      }
      if (userTypeText.value === '老师') {
        router.push('/teacher')
      }
      if (userTypeText.value === '管理员') {
        router.push('/admin')
      }
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error(error.message)
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-btn {
  width: 100%;
  margin-bottom: 10px;
}
</style>